<template>
	<div class="app-container" v-loading="data.mtloading">
		<el-form :model="data.info" :rules="data.rules" class="w-full mt-4" :label-width="language == 'en' ? '165' : '120'"
			ref="ruleFormRef">

			<div class="border border-[#4B8DF8]">
				<div class="bg-[#4B8DF8] p-2.5 text-[#fafafa] text-lg">{{ $t('goods.list.step') }}：{{
					$t('machine.configs.basic') }}</div>
				<div class="pt-4">

					<el-form-item :label="$t('machine.goods.name') + ':'" prop="g_name" class="w-1/2">
						<el-input v-model="data.info.g_name" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.pic') + ':'" prop="pic" class="w-1/2">
						<el-input v-model="data.info.pic" :placeholder="$t('message.pleaseEnter')" readonly>
							<template #append>
								<Upload :list="{ 'data': 'goods', 'list': false }" :type="1" :uptype="2"
									@exposeData="expose" />
							</template>
							<template #suffix>
								<el-icon class="ml-2" size="20" @click="urlimg(data.info.pic)">
									<Picture />
								</el-icon>
							</template>
						</el-input>
					</el-form-item>
					
					<el-form-item :label="$t('machine.goods.class') + ':'" prop="gc_id" class="w-1/2">
						<el-cascader v-model="data.info.gc_id" :options="data.typelist" :props="{ checkStrictly: true }"
							filterable clearable class="w-full" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.marque') + ':'" prop="model" class="w-1/2">
						<el-input v-model="data.info.model" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.type') + ':'" prop="g_type" class="w-1/2">
						<el-select v-model="data.info.g_type" :placeholder="$t('message.pleaseSelect')" clearable
							filterable @change="changeSelect">
							<el-option v-for="item in getPlevel.gType_list" :key="item.value" :label="$t(item.label)"
								:value="item.value" />
						</el-select>
					</el-form-item>

					<el-form-item :label="$t('machine.goods.barCode') + ':'" prop="bar_code" class="w-1/2">
						<el-input v-model="data.info.bar_code" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item label="SKU:" prop="sku" class="w-1/2">
						<el-input v-model="data.info.sku" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.associate') + 'SKU:'" prop="sku2" class="w-1/2">
						<el-input v-model="data.info.sku2" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.costPrice') + ':'" prop="cost_price" class="w-1/2">
						<el-input v-model="data.info.cost_price" :placeholder="$t('message.pleaseEnter')"
							type="number" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.marketValue') + ':'" prop="market_price" class="w-1/2">
						<el-input v-model="data.info.market_price" :placeholder="$t('message.pleaseEnter')"
							type="number" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.retailPrice') + ':'" prop="retail_price" class="w-1/2">
						<el-input v-model="data.info.retail_price" :placeholder="$t('message.pleaseEnter')"
							type="number" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.manufacturer') + ':'" prop="manufacturer" class="w-1/2">
						<el-input v-model="data.info.manufacturer" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.goods.phone') + ':'" prop="service_phone" class="w-1/2">
						<el-input v-model="data.info.service_phone" maxlength="11"
							:placeholder="$t('message.pleaseEnter')" />
					</el-form-item>
					<el-form-item :label="$t('machine.goods.bannerPic') + ':'" prop="banner" >
						<Upload :list="{ 'data': 'goods_banner', 'list': false }" :type="1" :uptype="6" @exposeData="exposes" />
						<div class="w-20 ml-4 relative" @mouseenter="handleMouseEnter(index,1)"
                            @mouseleave="handleMouseLeave(1)" v-for="(item, index) in data.uploadUrl" :key="index"><img :src="item" alt="">
                            <div v-if="uploadIndex == index"
                                class="flex absolute top-0 left-0 bg-[#808585ad] bottom-0 right-0">
                                <div class="self-center ml-8" @click="onDel(index,1)">
                                    <el-icon>
                                        <DeleteFilled color="#fff" />
                                    </el-icon>
                                </div>
                            </div>
                        </div>
					</el-form-item>

					<el-form-item :label="$t('machine.goods.detailsPic') + ':'" prop="details_pic" >
						<Upload :list="{ 'data': 'goods_banner', 'list': false }" :type="1" :uptype="6" @exposeData="exposeDetails" />
						<div class="w-20 ml-4 relative" @mouseenter="handleMouseEnter(index,2)"
                            @mouseleave="handleMouseLeave(2)" v-for="(item, index) in data.detailsUrl" :key="index"><img :src="item" alt="">
                            <div v-if="detailsIndex == index"
                                class="flex absolute top-0 left-0 bg-[#808585ad] bottom-0 right-0">
                                <div class="self-center ml-8" @click="onDel(index,2)">
                                    <el-icon>
                                        <DeleteFilled color="#fff" />
                                    </el-icon>
                                </div>
                            </div>
                        </div>
					</el-form-item>

					<el-form-item :label="$t('goods.list.desc') + ':'" prop="desc" class="w-full">
						<Editor v-model="data.info.desc" />
					</el-form-item>
				</div>
			</div>

			<div class="border border-[#FFB848] mt-6">
				<div class="bg-[#FFB848] p-2.5 text-[#fafafa] text-lg">{{ $t('goods.list.performance') }}</div>
				<div class="p-2 pt-4">
					<el-tag v-for="item of data.performance" type="warning" class="m-2 cursor-pointer" size="large"
						@click="addmance(item)">
						{{ item.cp_id }}-{{ item.name || $t('machine.types.undefined') }}
					</el-tag>
					<draggable :list="data.mancelist" item-key="cp_id" group="people">
						<template #item="item">
							<div class="border pb-4 mb-2">
								<div class="w-full relative flex flex-wrap ml-2 mt-4">
									<div class="w-2/12">
										<el-input v-model="item.element.name"
											:placeholder="$t('message.pleaseContents')" />
									</div>
									<div class="w-2/12 ml-4">
										<el-input v-model="item.element.variable"
											:placeholder="$t('message.pleaseFields')" />
									</div>
									<div class="w-4/12 ml-4">
										<el-input v-model="item.element.value"
											:placeholder="$t('message.pleaseContents')" />
									</div>
									<div class="w-2/12 ml-4">
										<el-select v-model="item.element.lang" :placeholder="$t('message.pleaseSelect')"
											filterable>
											<el-option v-for="item in data.langarr" :key="item.l_id"
												:label="item.name + '(' + item.lang + ')'" :value="item.lang" />
										</el-select>
									</div>
									<div class="ml-4 mt-1">
										<el-link type="danger" :underline="false" @click="dels(item.index)">{{
											$t('public.del')}}</el-link>
									</div>
								</div>
							</div>
						</template>
					</draggable>
					<div class="ml-2 mt-4">
						<el-tag class="cursor-pointer" type="warning" size="large" effect="dark" @click="setmance">
							{{ $t('goods.list.addPerformance') }}
						</el-tag>
					</div>
				</div>
			</div>

			<div class="border border-[#AF5CC1] mt-6">
				<div class="bg-[#AF5CC1] p-2.5 text-[#fafafa] text-lg">{{ $t('goods.list.optional') }}</div>
				<div class="p-2 pt-4">

					<el-form-item :label="$t('goods.list.distribution') + ':'" prop="sell_channel" class="w-1/2">
						<el-radio-group v-model="data.info.sell_channel">
							<el-radio :value="1" :label="1">{{ $t('goods.list.machine') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('goods.list.mall') }}</el-radio>
							<el-radio :value="3" :label="3">{{ $t('goods.list.machine') }} +
								{{ $t('goods.list.mall') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('goods.list.status') + ':'" prop="status" class="w-1/2">
						<el-radio-group v-model="data.info.status">
							<el-radio :value="1" :label="1">{{ $t('public.enable') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('public.disable') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('goods.list.allow') + ':'" prop="heat" class="w-1/2">
						<el-radio-group v-model="data.info.heat">
							<el-radio :value="0" :label="0">{{ $t('goods.list.notHeated') }}</el-radio>
							<el-radio :value="1" :label="1">{{ $t('goods.list.grade1') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('goods.list.grade2') }}</el-radio>
							<el-radio :value="3" :label="3">{{ $t('goods.list.grade3') }}</el-radio>
							<el-radio :value="4" :label="4">{{ $t('goods.list.grade4') }}</el-radio>
							<el-radio :value="5" :label="5">{{ $t('goods.list.grade5') }}</el-radio>
							<el-radio :value="6" :label="6">{{ $t('goods.list.grade6') }}</el-radio>
							<el-radio :value="7" :label="7">{{ $t('goods.list.grade7') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('goods.list.validity') + ':'" prop="is_recommend" class="w-1/2">
						<el-radio-group v-model="data.term">
							<el-radio :value="1" :label="1">{{ $t('public.open') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('public.close') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item v-if="data.term == 1" :label="$t('goods.list.period') + ':'" prop="expire_notice"
						class="w-1/2">
						<el-input v-model="data.info.expire_notice" :placeholder="$t('message.pleaseEnter')" />
					</el-form-item>

					<el-form-item :label="$t('machine.configs.recommendingGood') + ':'" prop="is_recommend" class="w-1/2">
						<el-radio-group v-model="data.info.is_recommend">
							<el-radio :value="1" :label="1">{{ $t('public.open') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('public.close') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('goods.list.gift') + ':'" prop="is_gift" class="w-1/2">
						<el-radio-group v-model="data.info.is_gift">
							<el-radio :value="1" :label="1">{{ $t('public.yes') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('public.no') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('goods.list.pack') + ':'" prop="length" class="w-11/12">
						<div class="w-full relative flex flex-wrap">
							<div class="w-3/12 mr-2">
								<el-input v-model="data.info.length" :placeholder="$t('message.pleaseEnter')">
									<template #append>
										mm/{{ $t('goods.list.length') }}
									</template>
								</el-input>
							</div>
							X
							<div class="w-3/12 ml-2 mr-2">
								<el-input v-model="data.info.width" :placeholder="$t('message.pleaseEnter')">
									<template #append>
										mm/{{ $t('goods.list.width') }}
									</template>
								</el-input>
							</div>
							X
							<div class="w-3/12 ml-2 mr-2">
								<el-input v-model="data.info.height" :placeholder="$t('message.pleaseEnter')">
									<template #append>
										mm/{{ $t('goods.list.height') }}
									</template>
								</el-input>
							</div>
						</div>
					</el-form-item>

					<el-form-item :label="$t('goods.list.groupNum') + ':'" prop="group_quantity" class="w-1/2">
						<el-input v-model="data.info.group_quantity" :placeholder="$t('message.pleaseEnter')"
							type="number" />
					</el-form-item>

					<el-form-item :label="$t('goods.list.recyclable') + ':'" prop="recoverable" class="w-1/2">
						<el-radio-group v-model="data.info.recoverable">
							<el-radio :value="1" :label="1">{{ $t('public.yes') }}</el-radio>
							<el-radio :value="2" :label="2">{{ $t('public.no') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item :label="$t('date.saleTime') + ':'" prop="release_time" class="w-1/2">
						<el-date-picker v-model="data.info.release_time" :disabled-date="disabledDate" type="date"
							:placeholder="$t('message.pleaseSelect')" format="YYYY/MM/DD" value-format="x"
							style="width: 100%;" />
					</el-form-item>

				</div>
			</div>

			<div class="w-full text-left mt-4 ml-6">
				<div class="inline-block">

					<el-button type="primary" size="small" @click="submit(ruleFormRef)">
						<template #default>
							<span class="text-sm">{{ $t('public.save') }}</span>
						</template>
					</el-button>

					<el-button size="small" @click="cancell">
						<template #default>
							<span class="text-sm">{{ $t('public.cancel') }}</span>
						</template>
					</el-button>

				</div>
			</div>
		</el-form>

		<!-- 图片展示 -->
		<el-dialog v-model="data.demonstrate" center width="30%">
			<div class="flex justify-center">
				<el-image class="max-w-80" :src="data.info.pic" fit="fill" />
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import Upload from '@/components/Upload/index.vue';
import draggable from "vuedraggable";
import Editor from '@/components/Editor/index.vue';
import getPlevel from '@/utils/level'
import { getperform, getlang } from '@/api/manage';
import { getListcategory, addgoods } from '@/api/goods';
import { useRouter } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
let router = useRouter()
let data = reactive({
	detailsUrl: [],
	uploadUrl: [],
	mtloading: false, // 加载
	demonstrate: false, // 图片弹窗
	typelist: [], // 商品分类
	goodstype: '', // 原始数据-分类
	performance: [], // 性能参数
	mancelist: [], // 性能参数列表
	langarr: [], // 语言列表
	term: 2, // 有限期开关，1开，2关
	original: '', // 原始数据-表单
	info: { // 商品信息
		g_name: '',
		gc_id: '',
		gc_name: '',
		model: '',
		bar_code: '',
		sku: '',
		sku2: '',
		pic: '',
		cost_price: '',
		market_price: '',
		retail_price: '',
		manufacturer: '',
		service_phone: '',
		desc: '',
		heat: 0,
		is_gift: 2,
		is_recommend: 2,
		recoverable: 1,
		performance: '',
		sell_channel: 1,
		expire_notice: 0,
		length: '',
		width: '',
		height: '',
		group_quantity: '',
		release_time: '',
		status: 1,
		ao_id: ''
	},
	rules: { // 表单验证
		g_name: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		gc_id: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		model: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		bar_code: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		sku: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		pic: { required: true, message: $t('message.pleaseUpload'), trigger: 'blur' },
		market_price: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		retail_price: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		manufacturer: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		length: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
	},
})
const uploadIndex = ref()
const detailsIndex = ref()
let exposes = (e) => {
    if (e.status == 200) {
        data.uploadUrl.push(e.file.response.data)
    }
}
let exposeDetails = (e) => {
    if (e.status == 200) {
        data.detailsUrl.push(e.file.response.data)
    }
}
let handleMouseEnter = (index: number,flng:number) => {
	if(flng == 1){
		uploadIndex.value = index
	}
    if(flng == 2){
		detailsIndex.value = index
	}
}
let handleMouseLeave = (flng:number) => {
	if(flng == 1){
		uploadIndex.value = null
	}
    if(flng == 2){
		detailsIndex.value = null
	}
}
let onDel = (index:number,flng:number) => {
	if(flng == 1){
		data.uploadUrl.splice(index, 1);
	}
    if(flng == 2){
		data.detailsUrl.splice(index, 1);
	}
}
// 获取列表信息
let getlist = () => {
	data.original = JSON.stringify(data.info)
	data.typelist = []
	let select = []
	// 获取分类信息
	getListcategory().then(res => {
		if (res.state == 200) {
			data.goodstype = JSON.stringify(res.data)
			for (let item of res.data) {
				select.push({
					label: item.gc_id + '-' + item.gc_name,
					value: item.gc_id,
					gc_pid: item.gc_pid,
					children: []
				})
			}
			select.forEach(item => {
				select.find((ime) => {
					if (ime.gc_pid == item.value) {
						item.children.push(ime)
					}
				});
			})
			for (let item of select) {
				if (item.gc_pid == 0) {
					data.typelist.push(item)
				}
			}
		}
	})

	// 获取性能参数
	getperform().then(res => {
		if (res.state == 200) {
			data.performance = res.data
		}
	})

	// 获取语言列表
	getlang().then(res => {
		if (res.state == 200) {
			data.langarr = res.data
		}
	})

}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 点击性能参数
let addmance = (e) => {
	data.mancelist.push({
		cp_id: e.cp_id,
		name: e.name,
		variable: e.field,
		lang: e.lang || data.langarr[0].lang,
		value: ''
	})
}

// 删除性能参数
let dels = (e) => {
	data.mancelist.splice(e, 1)
}

// 添加自定义性能
let setmance = () => {
	// 因空的cp_id会导致拖动时产生BUG
	// 因此添加自定义性能时，采用时间戳当cp_id
	// 如有更优方案可代替时间戳，欢迎修改调整
	// DKM 启上
	data.mancelist.push({
		// cp_id: '', // 产生BUG
		cp_id: new Date().getTime(),
		name: '',
		variable: '',
		lang: data.langarr[0].lang,
		value: ''
	})
}

// 上传返回
let expose = (e) => {
	if (e.status == 200) {
		data.info.pic = e.file.response.data
	} else {
		data.info.pic = ''
	}
}

// 查看图片
let urlimg = (e) => {
	if (e == '') {
		return;
	}
	data.demonstrate = true;
}

// 保存
let submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {
			let obj = JSON.parse(data.original)
			let type = JSON.parse(data.goodstype)
			let mancearr = []
			obj.gc_id = data.info.gc_id[data.info.gc_id.length - 1] || ''
			obj.release_time = Math.floor(data.info.release_time / 1000)

			for (let key in obj) {
				if (key != 'gc_id' && key != 'performance' && key != 'release_time') {
					obj[key] = data.info[key]
				}
			}

			for (let item of type) {
				if (item.gc_id == obj.gc_id) {
					obj.gc_name = item.gc_name
				}
			}

			for (let item of data.mancelist) {
				if (item.name != '' && item.value != '') {
					mancearr.push({
						name: item.name,
						variable: item.variable,
						value: item.value,
						lang: item.lang
					})
				}
			}

			if (data.term == 1) {
				if (obj.expire_notice == 0 || obj.expire_notice == '') {
					ElMessage({
						message: $t('message.pleaseEnterdate'),
						type: 'error'
					})
					return
				}
			} else {
				obj.expire_notice = 0
			}
			obj.details_pic = data.detailsUrl.join(';')
			obj.banner =  data.uploadUrl.join(';')
			obj.performance = JSON.stringify(mancearr)
			data.mtloading = true
			addgoods(obj).then(res => {
				if (res.state == 200) {
					data.mtloading = false
					ElMessage({
						message: $t('message.addSuccess'),
						type: 'success'
					})
					router.back()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
				data.mtloading = false
			}).catch(err=>{
				data.mtloading = false
			})
		}
	})
}

// 取消
let cancell = () => {
	data.info = JSON.parse(data.original)
	data.mancelist = []
	router.back()
}

getlist()

</script>
